package com.zhongxi.guoyuan.view.seller;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.seller.SellerExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.seller.InnerMallResult;
import com.zhongxi.guoyuan.entity.seller.SellerMallOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.widget.MyListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SellerExchangeBeanActivity extends BaseActivity implements MyScrollView.OnScrollListener {


    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.rl)
    RelativeLayout rl;
    @Bind(R.id.seller_exchange_scrollview)
    MyScrollView scrollView;
    @Bind(R.id.seller_exchange_name)
    TextView sellerExchangeName;
    @Bind(R.id.seller_exchange_apply)
    TextView sellerExchangeApply;
    @Bind(R.id.seller_exchange_id)
    TextView sellerExchangeId;
    @Bind(R.id.seller_exchange_ordernum)
    TextView sellerExchangeOrdernum;
    @Bind(R.id.seller_exchange_total)
    TextView sellerExchangeTotal;
    @Bind(R.id.seller_exchange_startTime)
    TextView sellerExchangeStartTime;
    @Bind(R.id.seller_exchange_endTime)
    TextView sellerExchangeEndTime;
    @Bind(R.id.seller_exchange_searchordernum)
    TextView sellerExchangeSearchordernum;
    @Bind(R.id.seller_exchange_searchtotal)
    TextView sellerExchangeSearchtotal;
    @Bind(R.id.seller_exchange_listview)
    MyListView sellerExchangeListview;

    private String type;

    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.et_clear)
    TextView etClear;
    @Bind(R.id.et_hint_text)
    TextView etHintText;
    @Bind(R.id.et_text_cancel)
    TextView etTextCancel;
    @Bind(R.id.iv_search)
    ImageView ivSearch;

    @Bind(R.id.text_nodata)
    TextView tvNodata;

    private InnerMallResult.ConsoleBean consoleBean;
    private DatePickerDialog dialog;
    private String startTime;
    private String endTime;
    private Map<String, String> map;

    private String userphone;
    private SellerExchangeAdapter adapter;
    private List<SellerMallOrderResult.OrderInfoBean> list;
    private boolean nomore;
    private String dateNowStr;


    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_seller_exchangebean);
        ButterKnife.bind(this);
        initTitle();
        tvTitle.setText("豆豆兑换供货商");

    }

    /***
     * 汇总统计
     */
    private void getData() {
        type = "total";
        getServer(Url.BUSINESSCENTER_INNERMALL, null, "", true, null, "get");
    }

    /***
     * 时间段内汇总统计
     */
    private void getQueryInfo() {
        map = new HashMap<>();
        if (CommonTool.TimeCompare(startTime, endTime)) {
            type = "queryInfo";
            map.clear();
            map.put("stime", startTime);
            map.put("etime", endTime);
            getServer(Url.BUSINESSCENTER_INNERMALL_BYTIME, map, "", true, null, "post");
        } else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    private void getOrderList() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.BUSINESSCENTER_ORDERLIST, null, str, true, null, "get");
    }

    private void getOrderQueryList() {
        type = "order";
        String str = "&page=" + pageNum + "&userphone=" + userphone;
        getServer(Url.BUSINESSCENTER_ORDERLIST, null, str, true, null, "get");
    }

    @Override
    protected void initData() {
        super.initData();
        getData();
        list = new ArrayList<>();
        adapter = new SellerExchangeAdapter(this);
        sellerExchangeListview.setAdapter(adapter);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        dateNowStr = sdf.format(now);
        sellerExchangeStartTime.setText(dateNowStr);
        sellerExchangeEndTime.setText(dateNowStr);
        startTime = endTime = dateNowStr;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        scrollView.setOnScrollListener(this);

        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    etTextCancel.setVisibility(View.VISIBLE);
                    etTextCancel.setText("取消");
                    etClear.setVisibility(View.GONE);
                    etHintText.setVisibility(View.GONE);
                }
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    etClear.setVisibility(View.VISIBLE);
                    etTextCancel.setText("搜索");
                } else {
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setText("取消");
                }
                etHintText.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("total")) {
            InnerMallResult result = gson.fromJson(response, InnerMallResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            initInfo(result);
            getQueryInfo();
        } else if (type.equals("queryInfo")) {
            InnerMallResult result = gson.fromJson(response, InnerMallResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            initQuery(result);
            getOrderList();
        } else if (type.equals("order")) {
            SellerMallOrderResult result = gson.fromJson(response, SellerMallOrderResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            if (pageNum == 1) {
                list.clear();
            }

            if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                list.addAll(result.getOrderInfo());
                adapter.setList(list);
                nomore = false;
                tvNodata.setVisibility(View.GONE);
                sellerExchangeListview.setVisibility(View.VISIBLE);
            } else {
                nomore = true;
                if (pageNum > 1) {
                    pageNum--;
                } else {
                    pageNum = 1;
                }

                if (list.size()>0){
                    tvNodata.setVisibility(View.GONE);
                    sellerExchangeListview.setVisibility(View.VISIBLE);
                }else {
                    tvNodata.setVisibility(View.VISIBLE);
                    sellerExchangeListview.setVisibility(View.GONE);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }

    private void initQuery(InnerMallResult result) {
        if (null != result.getOrderNum() && !"".equals(result.getOrderNum())) {
            sellerExchangeSearchordernum.setText(result.getOrderNum());
        } else {
            sellerExchangeSearchordernum.setText("0");
        }
        if (null != result.getInnerPrice() && !"".equals(result.getInnerPrice())) {
            sellerExchangeSearchtotal.setText(result.getInnerPrice());
        } else {
            sellerExchangeSearchtotal.setText("");
        }
    }

    private void initInfo(InnerMallResult result) {
        if (null != result && !"".equals(result)) {
            if (null != result.getConsole() && !"".equals(result.getConsole())) {
                consoleBean = result.getConsole();
                //商家标识
                if (null != consoleBean.getSid() && !"".equals(consoleBean.getSid())) {
                    sellerExchangeId.setText("ID：" + consoleBean.getSid());
                } else {
                    sellerExchangeId.setText("");
                }
                if (null != consoleBean.getName() && !"".equals(consoleBean.getName())) {
                    sellerExchangeName.setText(consoleBean.getName());
                } else {
                    sellerExchangeName.setText("");
                }
            }

            if (null != result.getOrderNum() && !"".equals(result.getOrderNum())) {
                sellerExchangeOrdernum.setText(result.getOrderNum());
            } else {
                sellerExchangeOrdernum.setText("0");
            }
            if (null != result.getInnerPrice() && !"".equals(result.getInnerPrice())) {
                sellerExchangeTotal.setText(result.getInnerPrice());
            } else {
                sellerExchangeTotal.setText("0");
            }
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        if (baseResponse.getCode() == 9002) {
            showShortToast("登录已失效，请重新登录");
            MyApplication.getInstance().sharedPrefrences.edit().putString("MDChangecredentials", "").commit();
            finish();
        }
    }
    @OnClick({R.id.ivBack, R.id.seller_exchange_apply, R.id.seller_exchange_startTime, R.id.seller_exchange_endTime,
            R.id.et_clear, R.id.et_search, R.id.et_text_cancel, R.id.iv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                onBackPressed();
                break;
            case R.id.seller_exchange_apply://美豆兑换，申请提现
                startAct(SellerMallExchangeActivity.class);
                break;
            case R.id.seller_exchange_startTime:
                showDateDialog(0);
                break;
            case R.id.seller_exchange_endTime:
                showDateDialog(1);
                break;
            case R.id.iv_search:
                pageNum = 1;
                userphone = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(userphone)) {
                    getOrderQueryList();
                } else {
                    getOrderList();
                }

                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_text_cancel:
                userphone = etSearch.getText().toString().trim();
                if (userphone.length() > 0) {
                    pageNum = 1;
                    if (!TextUtils.isEmpty(userphone)) {
                        getOrderQueryList();
                    } else {
                        getOrderList();
                    }
                } else {
                    etSearch.setText("");
                    etHintText.setVisibility(View.VISIBLE);
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setVisibility(View.GONE);
                    getOrderList();
                }
                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_clear:
                etSearch.setText("");
                etHintText.setVisibility(View.VISIBLE);
                etTextCancel.setText("取消");
                etTextCancel.setVisibility(View.VISIBLE);
                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_search:
                etTextCancel.setVisibility(View.VISIBLE);
                break;


        }
    }

    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String mon = month + 1 + "";
                String text = year + "-" + mon + "-" + dayOfMonth;

                text= CommonTool.TimeCompare(text,dateNowStr)?text:dateNowStr;
                if (index == 0) {
                    sellerExchangeStartTime.setText(text);
                    startTime = text;
                } else if (index == 1) {
                    sellerExchangeEndTime.setText(text);
                    endTime = text;
                }
                pageNum = 1;
                getQueryInfo();
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }


    @Override
    public void onScroll(int scrollY) {

    }

    long firstTime = 0;

    @Override
    public void scrollBottom() {
        if (!nomore) {
            userphone = etSearch.getText().toString().trim();
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 500) {
                pageNum++;
                if (!userphone.isEmpty()) {
                    getOrderQueryList();
                } else {
                    getOrderList();
                }
                firstTime = System.currentTimeMillis();
            }
        }
    }
}
